<template>
	<view class="submit-page">
		<!-- 表单区域  -->
		<form style="flex:1">
			<view class="form-item">
				<label class="label-item" for="number">报工人：</label>
				<text>{{ userInfo.nickName }}</text>
			</view>
			<view class="form-item">
				<label class="label-item" for="number">货位：</label>
				<input ref="areaNameRef" :focus="areaNameFocus" @focus="areaNameFocus=true" @blur="areaNameFocus=false" class="uni-input"  v-model="formData.areaName"></input>
			</view>
			<view class="orderList" v-if="dataList.length">
				<scroll-view :scroll-top="scrollTop" scroll-y="true" style="height: 100%;"  @scroll="scroll">
					<view v-for="(item,index) in dataList" :key="index" class="box_card" >
						<view class="closeBtn" @click="delItem(item,index)">
						❎
						</view>
						<view class="form-item" >
							<label class="label-item" for="order-number">单号：</label>
							<text style="color: red;">{{ item.workOrderNumber }}</text>
							<!-- <input class="uni-input" id="order-number" v-model="formData.workOrderNumber" placeholder="请输入订单号" ></input> -->
						</view>
						<view class="form-item">
							<label class="label-item" for="number">客户：</label>
							<text>{{ item.clientName }}</text>
						</view>
						<view class="form-item">
							<label class="label-item" for="number">数量：</label>
							<text>{{ item.length }}</text>
						</view>
						<view class="form-item" v-if="item.areaName">
							<label class="label-item" for="number">货位：</label>
							<text>{{ item.areaName }}</text>
						</view>
					<!-- 	<view class="form-item">
							<label class="label-item" for="number">工序：</label>
							<text>{{ item.process }}</text>
						</view> -->
					</view>	
				</scroll-view>
			</view>
			<view class="noData" v-else>点击扫描工单号</view>
			
		</form>
		<view class="btngroups">
			<button type="primary"  class="btns" @click="submitForm()">入库</button>
			<!-- <button type="primary"  class="btns">移库</button> -->
		<!-- 	<button type="default" class="btns" @click="restForm()">重置</button> -->
		</view>
		<scanCode></scanCode>
	</view>
</template>

<script>
import scanCode from '@/components/lg-scanCode/scanCode.vue';
export default {
	components: {
		scanCode
	},
	data() {
		return {
			scrollTop: 0,
			formData: {
				areaName:'',
				areaId: '',
				workOrderNumber: '',
				status: '包装',
				process: '包装'
			},
			workOrderNumber:"",
			dataList:[],
			areaNameFocus:false,
			current: 0,
			userInfo: {
				nickName: uni.getStorageSync('nickName'),
				username: uni.getStorageSync('username'),
			},
			id: ''
		};
	},
	onUnload() {
		// 移除监听事件
		uni.$off('PDAScan');
	},
	onLoad: function() {
		// var that = this;
		// //setStorageSync数据存储
		// that.setStorageSyncData()
		let token = uni.getStorageSync('token');
		console.log('t', token);
		if (!token) {
			navigateAfterSuccess('9', '登录失效,请重新登录');
		}
	},
	onShow() {
		let that = this;
		uni.$off('PDAScan'); // 每次进来先 移除全局自定义事件监听器
		uni.$on('PDAScan', res => {
			console.log('扫码结果：', res.code);
			if(this.areaNameFocus){
				this.getareaName(res.code)
			}else{
				
				this.getWorkNumber(res.code)
			}
			
		});
	},
	methods: {
		getWorkNumber(val){
			val=val.replace(/[\r\n]+/gm, "")
			uni.request({
					url: 'http://121.40.25.211:8080/qb/task/selectTask?workOrderNumber=' + val,
					method: 'GET',
					header: {
						'content-type': 'application/json',
						Authorization: uni.getStorageSync('token')
					},
					success: res => {
						console.log(res)
						if(res.data.code==200){
							let ret = res.data.data;
							if(!this.dataList.length){
								if(ret.length){
									this.dataList.push(ret)
								}else{
									uni.showToast({
										icon: 'none',
										title: "未查询到工单信息",
									});
								}
								
							}else{
								var index=this.dataList.findIndex(a=>a.workOrderNumber==ret.workOrderNumber)
								if(index!=-1){
									uni.showToast({
										icon: 'none',
										title: "请勿重复扫码",
									});
									return
								}
								this.dataList.push(ret)
								// if(this.dataList[0].number==ret.number){
								// 	this.dataList.push(ret)
								// }else{
									
								// 	uni.showToast({
								// 		icon: 'none',
								// 		title: "请选择销售单号相同的工单",
								// 	});
								// 	return
								// }
							}
							if(!!ret.workOrderNumber){
								this.formData = ret;
								this.formData.workOrderNumber = val;
								
								this.workOrderNumber+=val+','
								// this.areaNameFocus=true;
							}else{
								uni.showToast({
									icon: 'none',
									title: "未查询到工单信息",
								});
							}
							
						}else{
							uni.showToast({
								icon: 'none',
								title: "未查询到工单信息",
							});
						}
					},
					fail: function(err) {
						console.log(err);
						uni.showToast({
							icon: 'none',
							title: err,
						});
					}
				});
			
		},
		getareaName(val){
			val=val.replace(/[\r\n]+/gm, "")
			this.formData.areaName=""
			uni.request({
					url: 'http://121.40.25.211:8080/mes/wm/area/list?pageNum=1&pageSize=100&areaName='+val,
					method: 'GET',
					header: {
						'content-type': 'application/json',
						Authorization: uni.getStorageSync('token')
					},
					success: res => {
						// console.log( res);
						if(res.data.code==200){						
							if(res.data.rows.length){
								var index=res.data.rows.findIndex((a)=>a.areaName==val)
							
								if(index!=-1){
									this.formData.areaName=res.data.rows[index].areaName;
									this.formData.areaId=res.data.rows[index].areaId;
									this.areaNameFocus=false;
									// this.submitForm()
									uni.showToast({
										icon: 'none',
										title: "查询货位成功",
									});
								}
								if(index==-1){
									uni.showToast({
										icon: 'none',
										title: "未查询到货位",
									});
									return
								}
								
							}else{							
								uni.showToast({
									icon: 'none',
									title: "未查询到货位",
								});
							}
						}else{
							uni.showToast({
								icon: 'none',
								title: "查询货位失败",
							});
						}
					},
					fail: function(err) {
						console.log(err);
					}
				});
		},
		restForm(){
			this.areaNameFocus=false;
			this.workOrderNumber="";
			this.dataList=[];
			this.formData={
				areaName:'',
				areaId: '',
				workOrderNumber: '',
				status: '包装',
				process: '包装'
			}
			uni.showToast({
				icon: 'success',
				title: "重置成功",
			});
		},
		async submitForm(){
			if(!this.dataList.length){
				uni.showToast({
					icon: 'none',
					title: "请扫描工单",
				});
				return
			}
			var successNum=0;
			let promiseList = [];
			for(var i=0;i<this.dataList.length;i++){
				var item=this.dataList[i];
				var paramdata=Object.assign({},item);
				paramdata.status=paramdata.status=='发货'?'发货':'包装';
				paramdata.process= '包装';
				paramdata.processTime =this.formatDate(new Date(), "YYYY-mm-dd hh:mm:ss");
				paramdata.areaId=this.formData.areaId;
				paramdata.areaName=this.formData.areaName;
				// paramdata.productionTaskId=paramdata.productionTaskId;
			console.log('paramdata',paramdata)
				let promise = new Promise((resolve, reject) => {
					uni.request({
						url: 'http://121.40.25.211:8080/qb/task',
						method: 'PUT',
						data: paramdata,
						header: {
							'content-type': 'application/json',
							Authorization: uni.getStorageSync('token')
						},
						success: res =>{
							 if (res.data.code == 200) {
								successNum+=1
								resolve('操作成功')
							} else {
							  reject(res.data.msg||"入库失败")
							}
						},
						fail: function(err) {
							console.log(err);
							 reject(res.data.msg||"操作失败")
						},
						})
				});
				 promiseList.push(promise);
				
			}
			 await Promise.all(promiseList).then((res) => {
			          console.log("等所有异步请求完成后执行", res);
			          // 等所有异步请求完成后执行
			          uni.showToast({
			          	icon: 'success',
			          	title: "入库成功",
			          });
			        })
			        .catch((er) => {
						uni.showToast({
							icon: 'none',
							title: er||"入库失败",
						});
					})
			        .finally(() => {
			          console.log('then')
			          this.dataList=[];
					  this.workOrderNumber="";
			          this.areaNameFocus=false;
			          this.formData={
			          	areaName:'',
			          	areaId: '',
			          	workOrderNumber: '',
			          	status: '包装',
			          	process: '包装'
			         }
			        });
		},
		
		formatDate(value, type) {
		      // 计算日期相关值
		      let time = typeof value == "number" ? new Date(value) : value;
		      let Y = time.getFullYear();
		      let M = time.getMonth() + 1;
		      let D = time.getDate();
		      let h = time.getHours();
		      let m = time.getMinutes();
		      let s = time.getSeconds();
		      let week = time.getDay();
		      // 如果传递了type的话
		      if (type == undefined) {
		        return Y + "-" + (M < 10 ? "0" + M : M) + "-" + (D < 10 ? "0" + D : D);
		      } else if (type == "YYYY-mm-dd hh:mm:ss") {
		        // 在quartz中 1为星期日
		        return (
		          Y +
		          "-" +
		          (M < 10 ? "0" + M : M) +
		          "-" +
		          (D < 10 ? "0" + D : D) +
		          " " +
		          (h < 10 ? "0" + h : h) +
		          ":" +
		          (m < 10 ? "0" + m : m) +
		          ":" +
		          (s < 10 ? "0" + s : s)
		        );
		      } else if (type == "week") {
		        // 在quartz中 1为星期日
		        return week + 1;
		      }
		    },
		delItem(row,index){
			this.dataList.splice(index,1)
		},
		logout() {
			// 实现退出登录逻辑，可能包括清除本地存储的 token、向服务器发送登出请求等
			console.log('Logging out');
			try {
				uni.request({
					url: '/api/api.php',
					method: 'POST',
					data: {
						mode: 'login_out'
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						token: uni.getStorageSync('token')
					},
					success(res) {
						console.log(res);
						let ret = res.data;
						if (ret.code == 0) {
							uni.removeStorageSync('token');
							uni.removeStorageSync('craft'); //工序
							uni.removeStorageSync('username');
							uni.removeStorageSync('nickName');
							navigateAfterSuccess('loginout', '重新登录');
						} else {
							showErrorToast(ret.msg);
							return false;
						}
					},
					fail: function(err) {
						console.log(err);
					}
				});
			} catch (error) {
				// 处理登录失败逻辑，例如显示错误信息
				console.error('api failed:', error);
			}
			// 更新用户状态（此处仅做演示，实际应修改全局状态或使用 Vuex）
			this.userInfo.username = null;
		},
		scroll: function(e) {
			console.log(e);
			// this.old.scrollTop = e.detail.scrollTop;
		},
	}
};

function showErrorToast(message) {
	uni.showToast({
		icon: 'none',
		title: message
	});
}

function navigateAfterSuccess(flag = '', tmpmsg = '操作成功') {
	// 显示登录成功提示
	uni.showToast({
		title: tmpmsg,
		icon: 'success',
		duration: 1000 // 自定义持续时间
	});
	if (flag == '') {
		return 0;
	}
	// 使用 Promise 链接，等待提示消失后跳转
	new Promise(resolve => setTimeout(resolve, 1500)).then(() => {
		uni.navigateTo({
			url: '/pages/login/index'
		});
	});
}
</script>

<style scoped>
.submit-page {
	position: relative;
	margin-top: 15px;
	/* height: 100%; */
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	height:calc(90vh - 15px);
}


.form-item {
	margin-bottom: 10px;
	margin-left: 5px;
	display: flex;
	align-items: center;
}

.label-item {
	/* margin-right: 16px; */
	/* width: 70px; */
}
.orderList .form-item{
	margin-bottom: 5px;
}

.uni-input {
	width: calc(100% - 90px);
	height: 40px;
	font-size: 16px;
	border: 1px solid #ddd;
	border-radius: 4px;
	padding: 0 10px;
}
.btngroups{
	background-color: #FFFFFF;
	position: fixed;
	bottom: 0px;
	width: 100%;
}
.btns{
	width: 80vw;
	margin:15px auto;
	
}
.box_card{
	border: 1px solid #8F8F94;
	padding: 10px;
}
.noData{
	text-align: center;
	font-size: 18px;
	color: #bebebe;
}
.orderList{
	height: calc(100% - 120px);
	/* border: 1px solid #ddd; */
}
.closeBtn{
	float: right;
	margin-right: 20px;
}
</style>
